import React, { useState } from "react";
import { Input, Button, Select, Tag, DatePicker } from "antd";
import { PlusOutlined } from "@ant-design/icons";
import "./TodoForm.css";

interface TodoFormProps {
  onAdd: (
    text: string,
    priority: "low" | "medium" | "high",
    dueDate: string | null,
    tags: string[]
  ) => void;
}

const { Option } = Select;

const TodoForm: React.FC<TodoFormProps> = ({ onAdd }) => {
  const [text, setText] = useState("");
  const [priority, setPriority] = useState<"low" | "medium" | "high">("medium");
  const [dueDate, setDueDate] = useState<any>(null);
  const [tag, setTag] = useState("");
  const [tags, setTags] = useState<string[]>([]);

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    if (text.trim()) {
      onAdd(
        text,
        priority,
        dueDate ? dueDate.format("YYYY-MM-DD") : null,
        tags
      );
      setText("");
      setPriority("medium");
      setDueDate(null);
      setTags([]);
    }
  };

  const handleAddTag = (e: React.KeyboardEvent<HTMLInputElement>) => {
    if (e.key === "Enter" && tag.trim()) {
      e.preventDefault();
      if (!tags.includes(tag.trim())) {
        setTags([...tags, tag.trim()]);
      }
      setTag("");
    }
  };

  const handleDeleteTag = (tagToDelete: string) => {
    setTags(tags.filter((t) => t !== tagToDelete));
  };

  return (
    <form className="todo-form" onSubmit={handleSubmit}>
      <div className="form-row">
        <Input
          value={text}
          onChange={(e) => setText(e.target.value)}
          placeholder="添加新的待办事项..."
          className="todo-input"
        />
        <Select
          value={priority}
          onChange={(value) => setPriority(value)}
          className="priority-select"
        >
          <Option value="low">低</Option>
          <Option value="medium">中</Option>
          <Option value="high">高</Option>
        </Select>
      </div>
      <div className="form-row">
        <DatePicker
          value={dueDate}
          onChange={setDueDate}
          className="date-picker"
          placeholder="截止日期"
        />
        <Input
          value={tag}
          onChange={(e) => setTag(e.target.value)}
          onKeyDown={handleAddTag}
          placeholder="添加标签（回车确认）"
          className="tag-input"
        />
      </div>
      <div className="tags-container">
        {tags.map((t) => (
          <Tag
            key={t}
            closable
            onClose={() => handleDeleteTag(t)}
            className="tag-chip"
          >
            {t}
          </Tag>
        ))}
      </div>
      <Button
        type="primary"
        htmlType="submit"
        className="add-button"
        icon={<PlusOutlined />}
        disabled={!text.trim()}
        block
      >
        添加事项
      </Button>
    </form>
  );
};

export default TodoForm;
